package com.xoa.service.cms;

import com.xoa.dao.cms.CmsChannelInfoMapper;
import com.xoa.dao.cms.CmsDocumentInfoMapper;
import com.xoa.dao.cms.CmsSiteInfoMapper;
import com.xoa.model.cms.*;
import com.xoa.model.users.Users;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cyt on 2018/7/5.
 */
@Service
public class CmsChannelService {

    @Autowired
    CmsChannelInfoMapper channelInfoMapper;
    @Autowired
    CmsSiteInfoMapper siteInfoMapper;
    @Autowired
    CmsDocumentInfoMapper documentInfoMapper;

    /**
     * 添加栏目
     * @param channelInfo
     */
    public void addChannelInfo(HttpServletRequest request, CmsChannelInfo channelInfo){
        //TeeRequestInfo info = TeeRequestInfoContext.getRequestInfo();
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        channelInfo.setCrTime(new Date());
        channelInfo.setCrUserid(users.getUid());
        channelInfo.setCrUsername(users.getUserId());

        //判断是否存在重复标识
        CmsChannelInfo existObj = getChannelByIdentity(channelInfo.getChnlIdentity());
        if(existObj!=null){
            throw new RuntimeException("已存在标识为("+channelInfo.getChnlIdentity()+")的栏目，请更换其他标识");
        }

        //获取父级栏目信息
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andSidEqualTo(channelInfo.getParentChnl());
        List<CmsChannelInfo> cmsChannelInfos = channelInfoMapper.selectByExample(channelInfoExample);
        CmsChannelInfo parentChannel=new CmsChannelInfo();
        if (cmsChannelInfos.size()>0) {
            parentChannel=cmsChannelInfos.get(0);
        }
        channelInfoMapper.insertSelective(channelInfo);

        //栏目路径
        if(parentChannel==null){
            channelInfo.setPath("/"+channelInfo.getSid()+".ch");
        }else{
            if (parentChannel.getPath() == null) {
                channelInfo.setPath("/"+channelInfo.getSid()+".ch");
            }else{
                channelInfo.setPath(parentChannel.getPath()+"/"+channelInfo.getSid()+".ch");
            }

        }
        channelInfoMapper.updateByPrimaryKeySelective(channelInfo);
    }

    public CmsChannelInfo getChannelByIdentity(String identity){
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andChnlIdentityEqualTo(identity);
        List<CmsChannelInfo> cmsChannelInfos = channelInfoMapper.selectByExample(channelInfoExample);
        CmsChannelInfo cmsChannelInfo=null;
        if (cmsChannelInfos.size()>0) {
            cmsChannelInfo=cmsChannelInfos.get(0);
        }
        return cmsChannelInfo;
    }

    /**
     * 获取栏目信息
     * @param channelId
     * @return
     */
    public CmsChannelInfo getChannelInfo(int channelId){
        return (CmsChannelInfo) channelInfoMapper.selectByPrimaryKey(channelId);
    }

    /**
     * 获取顶级栏目
     * @param siteId
     * @param top
     * @return
     */
    public List<CmsChannelInfo> getTopChannels(int siteId, int top){

        return channelInfoMapper.getTopChannels(siteId);
    }


    /**
     * 获取某个栏目的子栏目
     * @param channelId
     * @param top
     * @return
     */
    public List<CmsChannelInfo> getChildChannels(int channelId, int top){

        return channelInfoMapper.getChildChannels(channelId);
    }



    /**
     * 获取某几个栏目
     * @param
     * @param top
     * @return
     */
    public List<CmsChannelInfo> getChannelsByIds(String ids, int top){
        Map<String,Object> map=new HashMap<>();
        String[] idarray=null;
        if (ids != null) {
             idarray = ids.split(",");

        }
        map.put("ids",idarray);
        return channelInfoMapper.getChannelsByIds(map);
    }


    /**
     * 获取栏目绝对路径
     * @param channelId
     * @return
     */
    public String getChannelAbsolutePath(int channelId){
        String path = "";
        CmsChannelInfo channelInfo = getChannelInfo(channelId);
        //SiteInfo siteInfo = (SiteInfo) simpleDaoSupport.get(SiteInfo.class, channelInfo.getSiteId());
        CmsSiteInfo siteInfo  =siteInfoMapper.selectByPrimaryKey(channelInfo.getSiteId());
        path+="/"+siteInfo.getFolder();

        String tmps[] = channelInfo.getPath().split("/");
        for(String tmp:tmps){
            if("".equals(tmp)){
                continue;
            }
            CmsChannelInfo ci = getChannelInfo(Integer.parseInt(tmp.split("\\.")[0]));
            path+="/"+ci.getFolder();
        }

        return path;
    }

    public String getChannelRootPath(int channelId){
        String path = "";
        CmsChannelInfo channelInfo = getChannelInfo(channelId);
        if(channelInfo==null){
            return "./";
        }
        String tmps[] = channelInfo.getPath().split("/");
        for(String tmp:tmps){
            if("".equals(tmp)){
                continue;
            }
            path+="../";
        }

        return path;
    }




    /**
     * 更新栏目基础信息
     * @param channelInfo
     */
    public void updateChannelInfo(CmsChannelInfo channelInfo){
        CmsChannelInfo entity = channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());

        //判断是否存在重复标识
        CmsChannelInfo existObj = getChannelByIdentity(channelInfo.getChnlIdentity());
        if(existObj!=null && !channelInfo.getChnlIdentity().equals(entity.getChnlIdentity())){
            throw new RuntimeException("已存在标识为("+channelInfo.getChnlIdentity()+")的栏目，请更换其他标识");
        }
        BeanUtils.copyProperties(channelInfo, entity, new String[]{"path","crUserid","crUsername","crTime","parentChnl","delFlag"});
        //simpleDaoSupport.update(entity);
        channelInfoMapper.updateByPrimaryKey(entity);
    }

    /**
     * 实际删除栏目
     * @param
     */
    public void delChannelInfo(List<String> paths){
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andPathIn(paths);
        //CmsChannelInfo entity = channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());
        // channelInfoMapper.updateByPrimaryKeySelective(entity);
        //CmsChannelInfo entity = channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());
     //  channelInfoMapper.delChannelInfo(channelInfo.getPath());
        channelInfoMapper.deleteByExample(channelInfoExample);
    }

    /**
     * 移至回收站
     * @param
     */
    public void moveToTrash(List<Integer> sids){
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andSidIn(sids);
        //CmsChannelInfo entity = channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());
        CmsChannelInfo entity = new CmsChannelInfo();
        entity.setDelFlag(1);
       // channelInfoMapper.updateByPrimaryKeySelective(entity);
        channelInfoMapper.updateByExampleSelective(entity,channelInfoExample);
    }

    /**
     * 从回收站还原
     * @param channelInfo
     */
    public void recycle(CmsChannelInfo channelInfo){
        CmsChannelInfo entity = channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());
        entity.setDelFlag(0);
        channelInfoMapper.updateByPrimaryKeySelective(entity);
    }

    /**
     * 移动栏目
     * @param channelInfo
     */
    public void moveChannel(CmsChannelInfo channelInfo){
        CmsChannelInfo entity = channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());
        boolean changedChnl = false;//是否改变了栏目层级结构
        if(channelInfo.getParentChnl()!=entity.getParentChnl()){
            changedChnl = true;
        }

        if(changedChnl){//更新该栏目及下属栏目的path路径
            CmsChannelInfo parentChannel = channelInfoMapper.selectByPrimaryKey(channelInfo.getParentChnl());

            List<CmsChannelInfo> chnlList = channelInfoMapper.selectByFields(entity.getPath());
            //新栏目的path路径
            String newPath = null;
            if(parentChannel==null){
                newPath = "/"+entity.getSid()+".ch";
            }else{
                newPath = parentChannel.getPath()+"/"+entity.getSid()+".ch";
            }
            //批量更新下属栏目的path
            for(CmsChannelInfo tmp:chnlList){
                tmp.setPath(tmp.getPath().replace(entity.getPath(), newPath));
                channelInfoMapper.updateByPrimaryKeySelective(tmp);
            }
            //然后更新当前栏目的path和parentChnl
            entity.setParentChnl(channelInfo.getParentChnl());
            entity.setPath(newPath);
            channelInfoMapper.updateByPrimaryKeySelective(entity);
        }
    }

    public void clearTrash(int siteId,int channelId){
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andSiteIdEqualTo(siteId);
        criteria.andParentChnlEqualTo(channelId);
        criteria.andDelFlagEqualTo(1);
        channelInfoMapper.deleteByExample(channelInfoExample);
    }

    public Map listChannels(int siteId, int channelId){
        Map data = new HashMap();
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andSiteIdEqualTo(siteId);
        criteria.andParentChnlEqualTo(channelId);
        criteria.andDelFlagEqualTo(0);
        channelInfoExample.setOrderByClause("SORT_NO ASC");
        List<CmsChannelInfo> chnls = channelInfoMapper.selectByExample(channelInfoExample);
        data.put("list", chnls);
        //获取路径
        String path = "";
        String idPath = "";

        CmsSiteInfo site = siteInfoMapper.selectByPrimaryKey(siteId);

        path = "/"+site.getSiteName();
        idPath = "/"+site.getSid()+".st";

        if(channelId!=0){//只取出站点的路径来
            CmsChannelInfoExample channelInfoExample2=new CmsChannelInfoExample();
            CmsChannelInfoExample.Criteria criteria2 = channelInfoExample2.createCriteria();
            criteria2.andSidEqualTo(channelId);
            List<CmsChannelInfo> chnls2 = channelInfoMapper.selectByExample(channelInfoExample2);
            CmsChannelInfo chnl =chnls2.get(0);
            idPath += chnl.getPath();

            //拼接名称路径
            String sp[] = chnl.getPath().split("/");
            for(String id:sp){
                if(!"".equals(id)){
                   // chnl = (CmsChannelInfo) simpleDaoSupport.get(CmsChannelInfo.class, TeeStringUtil.getInteger(id.split("\\.")[0], 0));
                    String s = id.split("\\.")[0];
                    if (s != null && s != "") {
                        chnl = channelInfoMapper.selectByPrimaryKey(Integer.parseInt(s));
                    }
                    path+="/"+chnl.getChnlName();
                }
            }
        }
        data.put("path", path);
        data.put("idPath", idPath);
        return data;
    }

    public Map listTrashChannels(int siteId, int channelId){
        Map data = new HashMap();
//        List<CmsChannelInfo> chnls = simpleDaoSupport.find("from ChannelInfo ci where ci.siteId="+siteId+" and ci.parentChnl="+channelId+" and ci.delFlag=1 order by ci.sortNo asc", null);
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andSiteIdEqualTo(siteId);
        criteria.andParentChnlEqualTo(channelId);
        criteria.andDelFlagEqualTo(1);
        channelInfoExample.setOrderByClause("SORT_NO ASC");
        List<CmsChannelInfo> chnls = channelInfoMapper.selectByExample(channelInfoExample);
        data.put("list", chnls);
        //获取路径
        String path = "";
        String idPath = "";

       // SiteInfo site = (SiteInfo) simpleDaoSupport.get(SiteInfo.class, siteId);
        CmsSiteInfo site =siteInfoMapper.selectByPrimaryKey(siteId);

        path = "/"+site.getSiteName();
        idPath = "/"+site.getSid()+".st";

        if(channelId!=0){//只取出站点的路径来
           // CmsChannelInfo chnl = (CmsChannelInfo) simpleDaoSupport.get(CmsChannelInfo.class, channelId);

            CmsChannelInfoExample channelInfoExample2=new CmsChannelInfoExample();
            CmsChannelInfoExample.Criteria criteria2 = channelInfoExample2.createCriteria();
            criteria2.andSidEqualTo(channelId);
            List<CmsChannelInfo> chnls2 = channelInfoMapper.selectByExample(channelInfoExample2);
            if (chnls2.size() > 0) {
                CmsChannelInfo chnl =chnls2.get(0);
                idPath += chnl.getPath();
                //拼接名称路径
                String sp[] = chnl.getPath().split("/");
                for(String id:sp){
                    if(!"".equals(id)){
                        String s = id.split("\\.")[0];
                        if (s != null && s != "") {
                            chnl = channelInfoMapper.selectByPrimaryKey(Integer.parseInt(s));
                        }
                        //chnl = (CmsChannelInfo) simpleDaoSupport.get(CmsChannelInfo.class, TeeStringUtil.getInteger(id.split("\\.")[0], 0));
                        path+="/"+chnl.getChnlName();
                    }
                }
            }
            }

        data.put("path", path);
        data.put("idPath", idPath);

        return data;
    }


    /**
     * 复制栏目
     * @param channelInfo
     */
    public void copyChannel(CmsChannelInfo channelInfo) {
       // CmsChannelInfo entity = (CmsChannelInfo) simpleDaoSupport.get(CmsChannelInfo.class, channelInfo.getSid());

        CmsChannelInfo entity= channelInfoMapper.selectByPrimaryKey(channelInfo.getSid());
        boolean changedChnl = false;//是否改变了栏目层级结构
        if(channelInfo.getParentChnl()!=entity.getParentChnl()){
            changedChnl = true;
        }

        if(changedChnl){//更新该栏目及下属栏目的path路径
           // CmsChannelInfo parentChannel = (CmsChannelInfo) simpleDaoSupport.unique("from CmsChannelInfo ci where ci.sid="+channelInfo.getParentChnl(), null);
            CmsChannelInfo parentChannel= channelInfoMapper.selectByPrimaryKey(channelInfo.getParentChnl());

            //List<CmsChannelInfo> chnlList = simpleDaoSupport.find("from ChannelInfo ci where ci.path like '"+entity.getPath()+"/%'", null);
            List<CmsChannelInfo> chnlList=channelInfoMapper.selectByFields(entity.getPath());

            CmsChannelInfo newChannel = new CmsChannelInfo();
            BeanUtils.copyProperties(entity, newChannel);
            //复制栏目
            //simpleDaoSupport.save(newChannel);
            channelInfoMapper.insertSelective(newChannel);


            //新栏目的path路径
            String newPath = null;
            if(parentChannel==null){
                newPath = "/"+newChannel.getSid()+".ch";
            }else{
                newPath = parentChannel.getPath()+"/"+newChannel.getSid()+".ch";
            }

		/*	//批量更新下属栏目的path
			for(ChannelInfo tmp:chnlList){
				ChannelInfo newTmp = new ChannelInfo();
				BeanUtils.copyProperties(tmp, newTmp);
				newTmp.setPath(tmp.getPath().replace(entity.getPath(), newPath));
				simpleDaoSupport.save(newTmp);

				String oldPath = newTmp.getPath();
				String[] oldPaths = oldPath.split("/");
				String oldSid = oldPaths[oldPaths.length-1];
				newTmp.setPath(newTmp.getPath().replace(oldSid, newTmp.getSid()+".ch"));
				String parentPath = oldPaths[oldPaths.length-2];
				int pid = Integer.parseInt(parentPath.split("\\.")[0]);
				newTmp.setParentChnl(pid);
				simpleDaoSupport.update(newTmp);
			}*/
            dealChildChannel(entity.getSid(),newPath);

            newChannel.setParentChnl(channelInfo.getParentChnl());
            newChannel.setPath(newPath);
            newChannel.setChnlIdentity(entity.getChnlIdentity()+(int)((Math.random()*9+1)*100000));
            //simpleDaoSupport.update(newChannel);
            channelInfoMapper.updateByPrimaryKeySelective(newChannel);
        }

    }

    public void dealChildChannel(int channelId,String newPath){
        //CmsChannelInfo entity = (CmsChannelInfo) simpleDaoSupport.get(CmsChannelInfo.class,channelId);
        CmsChannelInfoExample channelInfoExample=new CmsChannelInfoExample();
        CmsChannelInfoExample.Criteria criteria = channelInfoExample.createCriteria();
        criteria.andParentChnlEqualTo(channelId);
        List<CmsChannelInfo> chnls = channelInfoMapper.selectByExample(channelInfoExample);
        CmsChannelInfo entity=chnls.get(0);
        List<CmsChannelInfo> childList = this.getChildChannels(channelId, Integer.MAX_VALUE);
        for(CmsChannelInfo tmp:childList){
            CmsChannelInfo newTmp = new CmsChannelInfo();
            BeanUtils.copyProperties(tmp, newTmp);
            newTmp.setPath(tmp.getPath().replace(entity.getPath(), newPath));
            newTmp.setChnlIdentity(tmp.getChnlIdentity()+(int)((Math.random()*9+1)*100000));
//            simpleDaoSupport.save(newTmp);
            channelInfoMapper.insertSelective(newTmp);
            String oldPath = newTmp.getPath();
            String[] oldPaths = oldPath.split("/");
            String oldSid = oldPaths[oldPaths.length-1];
            newTmp.setPath(newTmp.getPath().replace(oldSid, newTmp.getSid()+".ch"));
            String parentPath = oldPaths[oldPaths.length-2];
            int pid = Integer.parseInt(parentPath.split("\\.")[0]);
            newTmp.setParentChnl(pid);
           // simpleDaoSupport.update(newTmp);
            channelInfoMapper.updateByPrimaryKeySelective(newTmp);
            //递归处理下级栏目
            String path = newTmp.getPath();
            dealChildChannel(tmp.getSid(),path);

        }

    }



    /**
     * @作者: Administrator
     * @时间: 2019/5/24
     * @说明: 根据栏目id 更新栏目状态
     */
    public BaseWrapper updateStatus(CmsChannelInfo cmsChannelInfo,String sids){
        BaseWrapper baseWrapper = new BaseWrapper();
        if(!StringUtils.checkNull(sids)){
            channelInfoMapper.updateStatusByIds(sids.split(","),cmsChannelInfo.getStatus());
        }else if(cmsChannelInfo.getSid()!=null&&cmsChannelInfo.getSid()!=0){
            channelInfoMapper.updateByPrimaryKeySelective(cmsChannelInfo);
        }
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("ok");
        return baseWrapper;
    }

    /**
     * @作者: Administrator
     * @时间: 2019/5/24
     * @说明: 根据站点id获取已发布的栏目
     */
    public BaseWrapper getChannelInfos(Integer siteId){
        BaseWrapper baseWrapper = new BaseWrapper();
        List<CmsChannelInfo> chnls = channelInfoMapper.getChannelInfos(siteId);
        baseWrapper.setData(chnls);
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("ok");
        return baseWrapper;
    }

    public BaseWrapper geiChannelInfoById(Integer channelId){
        BaseWrapper baseWrapper = new BaseWrapper();
        CmsChannelInfo cmsChannelInfo = channelInfoMapper.selectByPrimaryKey(channelId);
        baseWrapper.setData(cmsChannelInfo);
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("ok");
        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/06/04
     * @说明: 根据站点id获取已发布的栏目 以及包括五条最新信息 用于首页
     */
    public BaseWrapper getIndexChannelDocs(Integer siteId){
        BaseWrapper baseWrapper = new BaseWrapper();
        // 获取所有栏目（已发布）
        List<CmsChannelInfo> chnls = channelInfoMapper.getChannelInfos(siteId);

        PageParams pageParams = new PageParams();
        pageParams.setPage(1);
        pageParams.setPageSize(5);
        pageParams.setUseFlag(true);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("page",pageParams);

        // 便利循环 获取栏目下的文档信息（已发布）
        for (int i=0,size=chnls.size();i<size;i++){
            CmsChannelInfo cmsChannelInfo = chnls.get(i);

            map.put("chnlId",cmsChannelInfo.getSid());

            List<CmsDocumentInfoWithBLOBs> cmsDocumentInfoWithBLOBs = documentInfoMapper.selCmsDocs(map);

            cmsChannelInfo.setDocumentInfos(cmsDocumentInfoWithBLOBs);
        }

        baseWrapper.setData(chnls);
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("ok");
        return baseWrapper;
    }

}
